<template>
  <div class="table-pagination" ref="tablePagination">
    <div class="table">
      <el-table :data="tableData" :size="size" :height="tableHeight" border stripe style="width: 100%">
        <template v-for="(item, index) in columns">
          <el-table-column :prop="item.key" :label="item.label" :width="item.width"></el-table-column>
        </template>
      </el-table>
    </div>
    <div class="pagination" ref="pagination">
      <el-pagination
          @size-change="changePageSize"
          @current-change="changePage"
          :current-page="currentPage"
          :page-sizes="pageSizeOpt"
          :page-size="currentPageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.length">
      </el-pagination>
    </div>
  </div>
</template>

<script>
  export default {
    name: "tablePagination",
    props: {
      tableData: {
        type: Array,
        default: []
      },
      columns: {
        type: Array,
        default: []
      },
      size: {
        type: String,
        default: 'small'
      }
    },
    data() {
      return {
        currentPageSize: 10,
        currentPage: 1,
        pageSizeOpt: [10, 20, 50, 100],
        tableHeight: 200
      }
    },
    methods: {
      changePage(val) {
        this.currentPage = val;
        this.getTableData();
      },
      changePageSize(val) {
        this.currentPageSize = val;
        this.getTableData();
      },
      getTableData() {
        this.$emit('getTableData', {
          page: this.currentPage,
          pageSize: this.currentPageSize
        })
      },
      initTableHeight() {
        this.tableHeight = this.$refs.tablePagination.clientHeight - this.$refs.pagination?.clientHeight || 0;
      }
    },
    mounted() {
      this.$nextTick(() => {
        this.initTableHeight();
        window.addEventListener('resize', this.initTableHeight);
      });
    },
    activated() {
      window.addEventListener('resize', this.initTableHeight);
    },
    deactivated() {
      window.removeEventListener('resize', this.initTableHeight);
    },
    beforeDestroy() {
      window.removeEventListener('resize', this.initTableHeight);
    }
  }
</script>

<style scoped lang="scss">
.table-pagination{
  flex: 1;
  display: flex;
  flex-direction: column;
  .table{
    flex: 1;
  }
  .pagination{
    text-align: right;
  }
}
</style>
